package cn.wit.summit.chwan.utils;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 过滤器
 */
public class NameLengthFilter implements InputFilter {
    int MAX_EN;
    String regEx = "[\\u4e00-\\u9fa5]";
    String regEx2 = "[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]|[\\u2600-\\u27ff]";
    Context mContext;
    Pattern p = Pattern.compile(regEx);
    Pattern p2 = Pattern.compile(regEx2);

    public NameLengthFilter(int mAX_EN, Context context) {
        super();
        MAX_EN = mAX_EN;
        mContext = context;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart, int dend) {
        Matcher m1 = p2.matcher(source);
        if (m1.find()) {
            ToastUtils.getInstance(mContext).showToastSystem("不支持表情");
        }
        int destCount = dest.toString().length()
                + getChineseCount(dest.toString());
        int sourceCount = source.toString().length()
                + getChineseCount(source.toString());
        if (destCount + sourceCount > MAX_EN) {
            int surplusCount = MAX_EN - destCount;
            String result = "";
            int index = 0;
            while (surplusCount > 0) {
                char c = source.charAt(index);
                if (isChinest(c + "")) {
                    if (sourceCount >= 2) {
                        result += c;
                    }
                    surplusCount = surplusCount - 2;
                } else {
                    result += c;
                    surplusCount = surplusCount - 1;
                }
                index++;
            }
            return result;
        } else {
            return source;
        }

    }

    private int getChineseCount(String str) {
        int count = 0;
        Matcher m = p.matcher(str);
        while (m.find()) {
            for (int i = 0; i <= m.groupCount(); i++) {
                count = count + 1;
            }

        }
        return count;
    }

    private boolean isChinest(String source) {
        return Pattern.matches(regEx, source);
    }
}